import Highcharts from 'highcharts';
import React, {Component} from 'react';

export default class MiniChartWidget extends Component {
  refreshChart(props) {
    let options = Highcharts.merge(props.defaultOptions, props.options);
    options.chart.renderTo = this.refs.root;

    if (props.data && props.data.length) {
      options = Highcharts.merge(options, {
        series: [{
          data: props.data,
          pointStart: 1
        }]
      });
    }

    this.destroyChart();
    this.chart = new Highcharts.Chart(options);
  }

  destroyChart() {
    if (this.chart) {
      this.chart.destroy();

      this.chart=null;
    }
  }

  componentDidMount() {
    this.refreshChart(this.props);
  }

  componentWillReceiveProps(nextProps,prevProps) {
    this.refreshChart(nextProps);
  }

  componeneWillUnmount() {
    this.destroyChart();
  }

  render() {
    return <div ref="root" />;
  }
}

MiniChartWidget.defaultProps = {
  data:[],
  defaultOptions: {
    chart: {
      renderTo: null,
      backgroundColor: null,
      borderWidth: 0,
      type: 'line',
      margin: [2, 0, 2, 0],
      height: 20,
      style: {
        overflow: 'visible'
      },
      skipClone: true
    },
    title: {
      text: ''
    },
    credits: {
      enabled: false
    },
    series: [{
      data: [],
      pointStart: 1
    }],
    xAxis: {
      lineWidth: 0,
      labels: {
        enabled: false
      },
      title: {
        text: null
      },
      startOnTick: false,
      endOnTick: false,
      tickPositions: []
    },
    yAxis: {
      endOnTick: false,
      startOnTick: false,
      gridLineWidth: 0,
      labels: {
        enabled: false
      },
      title: {
        text: null
      },
      tickPositions: [0]
    },
    legend: {
      enabled: false
    },
    tooltip: {
      enabled:false
    },
    plotOptions: {
      series: {
        animation: false,
        lineWidth: 2,
        shadow: false,
        states: {
          hover: {
            lineWidth: 2
          }
        },
        marker: {
          radius: 1,
          states: {
            hover: {
              radius: 2
            }
          }
        },
        fillOpacity: 0.25
      },
      column: {
        negativeColor: '#910000',
        borderColor: 'silver'
      }
    }
  }
}
